<template>
  <div class="app-container">
    <div class="query-wrapper" model="queryParams">
      <el-select v-model="queryParams.vesselName" filterable clearable placeholder="Vessel" style="width: 180px;"
        @change="selectVessel(queryParams)">
        <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
        </el-option>
      </el-select>
      &nbsp;&nbsp;
      <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" style="width: 100px;">
        <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
        </el-option>
      </el-select>
      &nbsp;&nbsp;
      <el-select v-model="queryParams.pol" filterable clearable allow-create placeholder="POL" remote
        :remote-method="portName => { searchByPortName( portName) }"  >
        <el-option :key="item" :label="item" :value="item" v-for="item in ports" />
      </el-select>
      &nbsp;&nbsp;
      <el-select v-model="queryParams.pod" filterable clearable allow-create placeholder="POD" remote
        :remote-method="portName => { searchByPortName( portName) }"  > 
        <el-option :key="item" :label="item" :value="item" v-for="item in ports" />
      </el-select>
      &nbsp;&nbsp; 
      <el-button type="primary" icon="Search" @click="search">{{
        $t("ship.button.search")
        }}</el-button>
         <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
      <span>&nbsp;&nbsp;</span>
      <el-button type="primary" plain icon="Plus" @click="addClickEvent" v-hasPermi="['schedule:edit']">
        Create 
      </el-button>
      &nbsp;&nbsp;
      <el-dropdown placement="bottom-start" v-if="listData.length != 0">
      <el-button type="warning" icon="download" :disabled="listData.length == 0" v-hasPermi="['schedule:export']">
          Export
        </el-button> 
        <template #dropdown>
          <el-dropdown-menu>
              <el-dropdown-item :disabled="listData.length == 0" @click="exportClickEvent(0)">Complete</el-dropdown-item>
              <el-dropdown-item :disabled="listData.length == 0" @click="exportClickEvent(1)">Simplified</el-dropdown-item> 
               <el-dropdown-item :disabled="listData.length == 0" @click="exportEpdafda">EPDA & FDA</el-dropdown-item> 
            </el-dropdown-menu>
        </template>
    </el-dropdown>  
    </div>
    <br/>
    <div class="tips">
      <span>LOADING</span><el-button type="primary" circle
        style="width: 10px; height: 10px; border-radius: 50%;padding: 5px;"></el-button>
      <span>DISCHARGING</span><el-button type="danger" circle
        style="width: 10px; height: 10px; border-radius: 50%;padding: 5px;"></el-button>
      <span>LOADING + DISCHARGING</span><el-button type="warning" circle
        style="width: 10px; height: 10px; border-radius: 50%;padding: 5px;"></el-button>
    </div>
  </div>
  <el-table stripe row-key="scheduleId" :expand-row-keys="expandKeys" :data="listData"
    @row-dblclick="handleRowDblclick">

    <el-table-column type="expand" width="10">
      <template #default="props">
        <Detail :info="props.row" @click-port-name="onClickPortName" />
      </template>
    </el-table-column>

    <el-table-column prop="vesselName" label="Vessel Name">
      <template #default="scope">
        <div style="display: flex;align-items: center;" @click="onDetail(scope.row)">
          <el-icon class="el-icon-arrow-right" :class="{ expand: expandKeys.indexOf(scope.row.scheduleId) !== -1 }">
            <ArrowRight v-if="expandKeys.findIndex(r => r === scope.row.scheduleId) == -1" />
            <ArrowDown v-else />
          </el-icon>
          <span class="c-expand" style="text-align:center;">{{ scope.row.vesselName }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="voyageNo" label="Voyage No."><template #default="scope">
        <div style="text-align:center;">{{ scope.row.voyageNo }}</div>
      </template></el-table-column>

    <el-table-column prop="commencement" label="Commencement">
      <template #default="scope">
        <div @click="onQuick(scope.row)" style="width:100%;cursor:pointer;text-align:center;">&nbsp;
          <span>{{ scope.row.commenceTime ? convertDate(scope.row.commenceTime): " " }}</span>
        </div>
      </template>
    </el-table-column> 
    <el-table-column prop="completion" label="Completion">
      <template #default="scope">
        <div style="text-align:center;">{{ scope.row.completion }}</div>
      </template>
    </el-table-column>    
    <el-table-column prop="status" label="Status">
      <template #default="scope">
        <div style="text-align:center;">{{ statuss[scope.row.status] }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="createBy" label="Created By">
      <template #default="scope">
        <div style="text-align:center;">{{ scope.row.createBy }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="Time Created">
      <template #default="scope">
        <div style="text-align:center;">{{ scope.row.createTime }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="Operation" label="Operation" width="160" v-hasPermi="['schedule:edit']">
      <template #default="scope">
        <div style="text-align:center;"> 
          <span class="btn-primary" @click="editClickEvent(scope.row)">{{
            $t("ship.button.edit")
            }}</span>&nbsp;&nbsp;
          <span class="btn-primary" @click="removeClickEvent(scope.row.scheduleId)">{{
            $t("ship.button.remove")
            }}</span>
        </div>
      </template>
    </el-table-column>
  </el-table>
  <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
    @pagination="pageQuery" style="float: right" />

  <el-dialog destroy-on-close draggable :width="1280" :title="dialogTitle" v-model="dialogFormVisible" append-to-body @close="closeDialog">
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="6">
          <el-form-item label="Vessel Name" label-width="120px" prop="vesselName" required :rules="[
            { required: true, message: 'Vessel Name is required' }
          ]">
            <el-select v-model="formParam.vesselName" filterable placeholder="choose Vessel" @change="selectVoyage" style="width:100%">
              <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName"
                v-for="item in vessels">
              </el-option>
            </el-select>

          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="Voyage" label-width="120px" prop="voyageNo" required :rules="[
            { required: true, message: 'Voyage is required' }
          ]">
            <el-input type="number" :formatter="formatNumber" min="1" :parser="parseNumber"
              v-model="formParam.voyageNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="Status" label-width="120px" prop="status" required>
            <el-select v-model="formParam.status">
              <el-option :key="index" :label="item" :value="index" v-for="(item, index) in statuss" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
        <el-button style="margin-left: 20px;" @click="addItem()" type="primary" plain icon="Plus">Add Port</el-button>
        </el-col>
      </el-row>

      <div class="table-boxs">       
        <br /><br />
        <el-form class="table-box" :rules="rules" ref="formRef" :model="formObj">
          <el-table :data="formObj.recordData" class="detail-table-add" :row-key="(row) => row.id" ref="formTableRef" stripe
            :border="true">
            <el-table-column prop="seqNo" label="id" width="50" />
            <el-table-column label="Port" width="180px">
              <template #default="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.portName'" required :rules="rules.portRule">
                  <el-select v-model="scope.row.portName" filterable clearable placeholder="Port Name" remote
                    :remote-method="portName => { searchPortname(scope.row, portName) }" @change="onFormPort">
                    <el-option :key="item" :label="item" :value="item" v-for="item in scope.row.ports" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="defultRule" label="ETA"  width="160px">
              <template #default="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.eta'" required
                  :rules="[rules.etRule[0], { ...rules.etRule[1], row: scope.row }]">
                  <el-date-picker value-format="YYYY-MM-DD" v-model="scope.row.eta" class="ipt" placeholder=""
                    @change="onFormValid" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="defultRule" label="ETD" width="160px">
              <template #default="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.etd'"
                  :rules="[{ ...rules.etRule2[1], row: scope.row }]">
                  <el-date-picker value-format="YYYY-MM-DD" v-model="scope.row.etd" class="ipt" placeholder=""
                    @change="onFormValid" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="defultRule" label="ATA" width="160px">
              <template #default="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.ata'"
                  :rules="[rules.atRule[0], { ...rules.atRule[1], row: scope.row }]">
                  <el-date-picker value-format="YYYY-MM-DD" v-model="scope.row.ata" class="ipt" placeholder=""
                    @change="onFormValid" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="defultRule" label="ATD" width="160px">
              <template #default="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.atd'"
                  :rules="[rules.atRule2[0], { ...rules.atRule2[1], row: scope.row }]">
                  <el-date-picker value-format="YYYY-MM-DD" v-model="scope.row.atd" class="ipt" placeholder=""
                    @change="onFormValid" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="Activity">
              <template #default="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.activity'" :required="requiredKey" :rules="rules.defultRule">
                  <el-select v-model="scope.row.activity" multiple filterable clearable style="width:100%"  @change="changeRequired" collapse-tags>
                    <el-option :key="index" :label="item" :value="index" v-for="(item, index) in activitys" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="Operation" width="90">
              <template #default="scope">
                <el-button @click="deleteItem(scope.$index)" icon="Delete" />
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
          }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
          }}</el-button>
      </span>
    </template>
  </el-dialog>


  <el-dialog destroy-on-close draggable width="60%" title="commencement" v-model="dialogQuick" append-to-body>
    <el-form :model="formQuickParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="Time" label-width="120px" prop="commenceTime" required>
            <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" v-model="formQuickParam.commenceTime" type="datetime"
              placeholder="Select Date and Time" :default-value="convertTime(new Date())" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Location" label-width="120px" prop="commenceSite" required>
            <el-input v-model="formQuickParam.commenceSite" placeholder="Input location"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer" v-hasPermi="['schedule:edit']">
        <el-button @click="dialogQuick = false">{{ $t("ship.button.cancel") }}</el-button>
        <el-button type="primary" @click="submitQuictForm">{{ $t("ship.button.submit") }}</el-button>
      </span>
    </template>
  </el-dialog>

  <!--port 弹层信息--> 
  <el-dialog destroy-on-close draggable @close="closeHandle" :close-on-click-modal="false" :width="dialogWidth" v-model="dialogPort" class="schedule" append-to-body>
    <p class="header_title">{{ rowData.vesselName+' '+ rowData.voyageNo + ' ' +rowDataInfo.portName}}</p> 
    <el-tabs @tab-change="tabChange">
      <el-tab-pane label="GENERAL INFORMATION"   >
        <generalInformation ref="inForMationModal" v-if="activeTab == 0"  :data="detailData?.portRotation
        ?detailData.portRotation:{}" :titleValue="dialogPortTitle" @saveOk="saveOk"  @getDetail="resetDetail" />
      </el-tab-pane>
      <el-tab-pane label="PORT OPERATION RECORD">
        <portOperationRecordModal ref="operationRecordModal"  v-if="activeTab == 1"
           :data="detailData?.portOperationRecord?detailData.portOperationRecord:{}" 
           :titleValue="dialogPortTitle"
           :portRotationId="portRotationId" 
           @saveOk="saveOk" 
           @getDetail="resetDetail" />
      </el-tab-pane>

      <el-tab-pane label="BUNKER DATA"  >
         <bunkerInfo ref="bunkerInforef" v-if="activeTab == 2" 
            :portFormObj="portFormObj" 
            :rowData="rowData" 
            :titleValue="dialogPortTitle" 
            :portRotationId="portRotationId"  
            @saveOk="saveOk" 
            @getDetail="resetDetail" />

      </el-tab-pane>
      <el-tab-pane label="EPDA & FDA">
        <epdafdaInfo ref="epdafdaInforef" v-if="activeTab == 3" 
            :data="detailData?.epdaFda?detailData.epdaFda:{}" 
            :rowData="rowData" 
            :titleValue="dialogPortTitle" 
            :portRotationId="portRotationId" 
            @saveOk="saveOk" 
            @getDetail="resetDetail" />
      </el-tab-pane>
    </el-tabs>

  </el-dialog>
</template>
<script lang="ts" setup>
  // @ts-nocheck
  import { ref, onMounted, onBeforeUnmount, computed, reactive, nextTick } from "vue";
  import { ElMessage } from 'element-plus'
  import { RefreshLeft } from '@element-plus/icons-vue'
  import useDataMapStore from '@/store/modules/dataMap'
  import { convertDate, convertTime } from '@/utils/date'
  // 引入我们封装的 表单拖拽函数
  import { enableRowDrop } from '@/utils/sortable'  
  import { downloadFile } from "@/utils/downloadFile";
  const tableRef = ref();
  const formTableRef = ref();
  import service from "@/utils/request";
  import Sortable from 'sortablejs';
  import { ElNotification, ElMessageBox } from "element-plus";
  import Detail from './detail.vue'
  import generalInformation from './generalInformation';
  import portOperationRecordModal from './portOperationRecord'
  import epdafdaInfo from "./epdaFdaInfo.vue";

  import bunkerInfo from "./bunkerInfo.vue";

  import SearchReset from '@/components/SearchReset/index.vue'
  import DragUpload from '@/components/FormDataIUpload/index.vue'; 
  const activitys = ["LOADING", "DISCHARGING", "BUNKERING", "D/D or SURVEY", "CREW CHANGE","PASSING"]
  const placeholderText=" Upload File "
  const formWidth = ref(120)

  const dialogPort = ref(false)
  let dialogPortTitle = ref('')
  let portRotationId = ref(null)
  let portFormObj = ref({
    id: null,
    recordData: [
      {
        name: 'ROB ARR\n(mt)',
        VLSFO: null,
        PRICE: null,
        LSMGO: null,
        PRICE: null,
        LNG: null,
        PRICE: null,
        OTHERFEE: null,
        OTHERFEE: null,
        DATETIME: null,
        BDN: null,
        INVOICE: null,
        DATEISSUE: null,
        DATEPAID: null,
        BANKSLIP: null
      },
      {
        name: 'ROB DEP\n(mt)',
        VLSFO: null,
        PRICE: null,
        LSMGO: null,
        PRICE: null,
        LNG: null,
        PRICE: null,
        OTHERFEE: null,
        DATETIME: null,
        BDN: null,
        INVOICE: null,
        DATEISSUE: null,
        DATEPAID: null,
        BANKSLIP: null,
        DUEDATE:null
      },
      {
        name: 'SUPPLIED\n(mt)',
        VLSFO: null,
        VLSFOPRICE: null,
        LSMGO: null,
        LSMGOPRICE: null,
        LNG: null,
        LNGPRICE: null,
        OTHERFEE: null,
        DATETIME: null,
        BDN: null,
        INVOICE: null,
        DATEISSUE: null,
        DATEPAID: null,
        BANKSLIP: null,
        DUEDATE:null
      },
      {
        name: '',
        VLSFO: null,
        VLSFOPRICE: null,
        LSMGO: null,
        LSMGOPRICE: null,
        LNG: null,
        LNGPRICE: null,
        OTHERFEE: null,
        DATETIME: null,
        BDN: null,
        INVOICE: null,
        DATEISSUE: null,
        DATEPAID: null,
        BANKSLIP: null,
        DUEDATE:null
      },{
        name: '',
        VLSFO: null,
        VLSFOPRICE: null,
        LSMGO: null,
        LSMGOPRICE: null,
        LNG: null,
        LNGPRICE: null,
        OTHERFEE: null,
        DATETIME: null,
        BDN: null,
        INVOICE: null,
        DATEISSUE: null,
        DATEPAID: null,
        BANKSLIP: null,
        DUEDATE:null
      }
    ]
  })
  const requiredKey = ref(false)

  const changeRequired = () => {
    requiredKey.value = true
  }

  const closeDialog = () => {
    requiredKey.value = false
  }

  const rowData = ref()
  const rowDataInfo = ref()
  const onClickPortName = ({ row, titleValue, id }) => { 
    const info = row.details.find(item => { return item.id == id })
    rowDataInfo.value = info
    getDetail(info.id)
    portRotationId.value = info.id
    rowData.value = row 
    dialogPortTitle.value = titleValue
    activeTab.value=0
    dialogPort.value = true
  }

  const formatNumber = (value) => {
    if (value) {
      if (value.length == 1||String(value).length == 1)
        return (value + "").padStart(3, '0')
      if (value.length == 2||String(value).length == 2)
        return (value + "").padStart(3, '0')
      return value
    }
    return ""
  }
  const parseNumber = (value) => {
    // 解析函数，从输入中提取数值
    return parseInt(value, 10) || 0;
  }

  
const closeHandle=()=>{
  detailData.value = Object.assign({}, {})
  dialogPort.value = false
}

  let vessels = reactive([] as any); 
  let voyages = reactive([] as any);
  const custForm = ref(null);
  const formRef = ref()
  const dialogTitle = ref("");
  const initForm = {
    scheduleId: null,
    voyageId: null,
    vesselName: null,
    voyageNo: null,
    details: [],
    status: 0,
  };
  const formParam = reactive(Object.assign({}, initForm));
  const formQuickParam = reactive(
    {
      scheduleId: null,
      commenceTime: null,
      commenceSite: null
    }
  );

  const total = ref(0);
  const portChange = ref(0);

  let ports = ref([])
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    voyageNo: null,
    vesselName: null,
    pol: null,
    pod: null,
    orderByColumn: undefined,
    isAsc: undefined,
  });

  const statuss = ["Active", "Canceled", "Closed"] as any;

  const listData = ref([]);
  const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value  = 0
  }
  const refreshTable = async () => {
    let result = await service.get("/shipping/schedule/getTable", { params: queryParams });
    listData.value = (result.data || []).map(({ columns, headers, ...rst }) => {
      headers = headers.map((item, index) => {
        return { [`p${index}`]: item }
      })

      columns = columns.map((item, index) => {
        const obj = {}
        item.map((subItem, sindex) => {
          obj[`p${sindex}`] = subItem
        })
        return obj
      })
      return {
        headers,
        columns,
        ...rst
      };
    });

    total.value = result.total;
  };

  let formObj = ref({
    recordData: [{
      seqNo: 1,
      portName: null,
      eta: null,
      acta: null,
      ports: []
    }
    ]
  })

  const queryRules = ref({
    voyageNo: [
      {
        required: true,
        message: 'please select Voyage'
      }
    ]
  })

  // 表格验证
  const rules = ref({
    defultRule: [
      {
        required: true,
        message: 'Mandatory Field'
      }
    ],
    portRule: [
      {
        required: true,
        message: 'please select Port Name'
      } 
    ],
    etRule: [
      {
        required: true,
        message: 'please select ETA '
      },
      {
        validator: (rule, value, callback) => {
			    //上下比较
          if( rule.row.seqNo >1){
              let dd=formObj.value.recordData[rule.row.seqNo-2];
              if (rule.row.eta != null && new Date(rule.row.eta).getTime()< new Date(dd.eta).getTime()) {
                callback(new Error("ETA need be later than previous"));
              } 
          }

          if (rule.row.eta && rule.row.etd) {
            if (rule.row.eta != null &&  new Date(rule.row.eta).getTime() > new Date(rule.row.etd).getTime()) {
              callback(new Error("ETA can't be later than ETD"));
            }
          }
          callback();
        }
      }
    ],
	etRule2: [
      {
        validator: (rule, value, callback) => {

        if(rule.row.seqNo  > 1){ 
          let dd=formObj.value.recordData[rule.row.seqNo -2];
          if (rule.row.etd !=null && new Date(rule.row.etd).getTime()< new Date(dd.etd).getTime()) {
            callback(new Error("ETA should be later than previous one"));
          } 
        }

          if (rule.row.eta  && rule.row.etd) {
            if (new Date(rule.row.eta).getTime() > new Date(rule.row.etd).getTime()) {
              callback(new Error("ETA can't be later than ETD"));
            }
          }
          callback();
        }
      }
    ],
    atRule: [
      {
        required: false,
        message: 'Mandatory Field'
      },
      {
        validator: (rule, value, callback) => {
		
          //上下比较 
          if(rule.row.seqNo > 1){
              let dd=formObj.value.recordData[rule.row.seqNo -2];
              if (rule.row.ata != null && new Date(rule.row.ata).getTime()< new Date(dd.ata).getTime()) {
                callback(new Error("ETA should be later than previous"));
              }
            //i++
          }
          if (rule.row.ata && rule.row.atd && rule.row.ata != rule.row.atd) {
            //将atd的格式修改为年月日
            if (new Date(rule.row.ata).getTime() > new Date(rule.row.atd.substring(10)).getTime()) {
              callback(new Error("ATA can't be later than ATD"));
            }
          }
          callback();
        }
      }
    ],
    atRule2: [
      {
        required: false,
        message: 'Mandatory Field'
      },
      {
        validator: (rule, value, callback) => {
		
			//上下比较
			//let i=1
        if(rule.row.seqNo  >  1){
            let dd=formObj.value.recordData[rule.row.seqNo -2];
            if (rule.row.atd != null && new Date(rule.row.atd).getTime()< new Date(dd.atd).getTime()) {
              callback(new Error("ETA should be later than previous one"));
            } 
        }
          if (rule.row.ata && rule.row.atd) {
            if (new Date(rule.row.ata).getTime() > new Date(rule.row.atd.substring(10)).getTime()) {
              callback(new Error("ATA can't be later than ATD"));
            }
          }
          callback();
        }
      }
    ]
	
  });

  const onFormPort = () => {
    onFormValid()
    portChange.value = 1

  }

  const onFormValid = () => {
    nextTick(() => {
      formRef.value.validate()
    })
  }

  const addItem = () => {
    let item: any = {
      seqNo: formObj.value.recordData.length + 1,
      portName: null,
      eta: null,
      acta: null,
      ports: []
    }
    formObj.value.recordData.push(item)
  }

  const deleteItem = (index) => {
    if (formObj.value.recordData != null && formObj.value.recordData.length > 1) {
      formObj.value.recordData.splice(index, 1);
    }
    for (let i in formObj.value.recordData) {
      formObj.value.recordData[i].seqNo = parseInt(i) + 1;
    }
  };
  const dialogQuick = ref(false);
  const dialogFormVisible = ref(false);

  const editClickEvent = (row: any) => {
    dialogTitle.value = "Update Schedule";
    dialogFormVisible.value = true;
    Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
    formObj.value.recordData = row.details.map(item => {
      return {
        ...item,
        ports: item.portName ? [item.portName] : []
      }
    })
    isAdd = false;
  };

  let isAdd = false;

  const addClickEvent = () => {
    dialogTitle.value = "Create Schedule";
    isAdd = true;
    dialogFormVisible.value = true;
    Object.assign(formParam, initForm);

    formObj.value.recordData = [
      {
        seqNo: 1,
        portName: null,
        eta: null,
        acta: null
      },
      {
        seqNo: 2,
        portName: null,
        eta: null,
        acta: null
      }
    ]
  };

  const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
  };

  const submitForm = () => {
    changeRequired()
    const status = formObj.value.recordData.find(item => !item.id)
    if (portChange.value == 1 && !status) {
      ElMessageBox.confirm("Confirm To Change Port?", "Confirmation Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
      }).then(async () => {
        saveSchedule()
      });
    } else {
      saveSchedule()
    }
  };

  const saveSchedule = () => {
    // @ts-ignore
    custForm.value.validate(async (valid) => {
      if (!valid) {
        // @ts-ignore
        ElNotification.warning({
          title: "Prompt information",
          message: "verification not success！",
          position: "bottom-right",
        });
        return;
      }
      // @ts-ignore
      formRef.value.validate(async (valid) => {
        if (!valid) {
          // @ts-ignore
          ElNotification.warning({
            title: "Prompt information",
            message: "verification not success！",
            position: "bottom-right"
          });
          return;
        }

        if (formObj.value.recordData.length === 0) {
          ElNotification.warning({
            title: "Prompt information",
            message: "data must input！",
            position: "bottom-right"
          });
          return;
        }
        if (formParam.voyageNo) {
          formParam.voyageNo = formatNumber(formParam.voyageNo)
        }
        formParam.details = formObj.value.recordData; 
        await service[isAdd ? "post" : "put"]("shipping/schedule", formParam);
        // @ts-ignore
        ElNotification.success({
          title: "Prompt information",
          message: "save successful!",
          position: "bottom-right",
        });
        dialogFormVisible.value = false;
        refreshTable();
      })
    })
  }

  const submitQuictForm = () => {
    let result = service.put("/shipping/schedule/update", formQuickParam);
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right",
    });
    dialogQuick.value = false;
    refreshTable();
  };

  const sortableRow = ref(null);
  const dialogWidth = ref('80%');
  const updateDialogWidth = () => {
  const width = window.innerWidth; 
  if(activeTab.value == 2){
    dialogWidth.value = width >= 1920 ? '80%' :width >= 1400?'90%': width >= 1180 ? '1100px' : '900px';
  }else{
    dialogWidth.value = width >= 1920 ? '70%' :width >= 1400?'80%': width >= 1180 ? '900px' : '600px';
  }
};
  // 组件挂载之后执行
  onMounted(async () => {
    onSortableRow();
    window.addEventListener('resize', updateDialogWidth);
    updateDialogWidth();
    service.get("/shipping/schedule/getAllSchedule", { params: queryParams }).then(result => {
      vessels = result.data
    })
  });

  watch(() => formTableRef.value,
    () => {
      onSortableRow()
    },
    { deep: true }
  )

  // 拖动表格行
  const onSortableRow = () => {
    if (formTableRef.value) {
      sortableRow.value = Sortable.create(
        formTableRef.value.$el.querySelector(".el-table__body-wrapper tbody"),
        {
          animation: 150,
          onEnd: ({ newIndex, oldIndex }) => {
            // 获取新的行位置
            const currRow = formObj.value.recordData.splice(oldIndex, 1)[0];
            // 重新排列行位置
            formObj.value.recordData.splice(newIndex, 0, currRow);
            for (let i in formObj.value.recordData) {
              formObj.value.recordData[i].seqNo = parseInt(i) + 1;
            }
          },
        }
      );
    }

  };

  // 销毁
  onBeforeUnmount(() => {
    if (sortableRow.value) {
      sortableRow.value.destroy();
      sortableRow.value = null;
    }
  });

  const pageQuery = async (e) => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };

  const expandKeys = ref < string[] > ([])
  const onDetail = (row: any) => {
    let idx = expandKeys.value.findIndex(r => r === row.scheduleId);
    if (idx !== -1) {
      expandKeys.value.splice(idx, 1); 
    } else {
      expandKeys.value.push(row.scheduleId); 
    }
  }
  const onQuick = (row: any) => {
    dialogQuick.value = true;
    formQuickParam["commenceTime"] = row["commenceTime"]
    formQuickParam["commenceSite"] = row["commenceSite"]
    Object.keys(initForm).forEach((k) => (formQuickParam[k] = row[k]));

  }

  // 双击表格记录行展开收起
  const handleRowDblclick = (row, column) => { 
    if (!['scheduleId', 'commencement', 'Operation'].includes(column.property)) {
      onDetail(row)
    }
  }

  const search = () => {
    if (queryParams.vesselName == null) {
      ElMessage.warning("please choose vessel  to query!")
      return;
    }
    refreshTable();
  };

  const onDragEnd = (event) => {
    const { newIndex, oldIndex } = event;
    const movedItem = formObj.value.recordData.splice(oldIndex, 1)[0];
    listData.value.splice(newIndex, 0, movedItem);
  };

  const removeClickEvent = (id) => {
    ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }).then(async () => {
      await service.delete(`shipping/schedule/${id}`);

      refreshTable();
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "Delete successfully!",
        position: "bottom-right",
      });
    });
  };

  const selectVoyage = async () => {
    if (isAdd) {
      let params = reactive({ vesselName: formParam.vesselName })
      let result = await service.get("/shipping/schedule/getVoyageNo", { params: params });
      if (result) {
        formParam.voyageNo = result.data
      }
    }
  }

  const selectVessel = (form) => {
    queryParams.voyageNo = null
    if (form.vesselName != null && form.vesselName != undefined) {
      let params = { vesselName: form.vesselName }
      let item = vessels.find(n => n.vesselName == form.vesselName)
      if (item) {
        voyages = item.schedules
      }
    }
  }

  const searchByPortName = async ( portName) => {
    if (portName && portName.length >= 1) {
      let result = await service.get("/shipping/port/getTable", { params: { pageNum: 1, pageSize: 20, portName } })
      if (result) {
        ports = result.data.map(item => item.portName);
      }
    }
  }

  const searchPortname = async (row, portName) => {
    if (portName && portName.length >= 1) {
      let result = await service.get("/shipping/port/getTable", { params: { pageNum: 1, pageSize: 20, portName } })
      if (result) {
        row.ports = result.data.map(item => item.portName);
      }
    }
  }

  const detailData = ref()
  const resetDetail=(id)=>{
    if(id){
      getDetail(id)
    }
  }
  const getDetail = async (id) => {
    const result = await service.get("shipping/schedule/getDetail/" + id);
    detailData.value = Object.assign(result.data, {})
    
    const {
      robArrVlsfo = null,
      robArrVlsfoPrice = null,
      robArrBankSlip = [],
      robArrInvoice = [],
      robArrLsmgo = null,
      robArrLsmgoPrice = null,
      robArrLng = null,
      robArrLngPrice = null,
      robArrOtherFee = null,
      robArrDate = null,
      robArrDateIssue = null,
      robArrDatePaid = null,
      robDepVlsfo = null,
      robDepVlsfoPrice = null,
      robDepLsmgo = null,
      robDepLsmgoPrice = null,
      robDepLng = null,
      robDepLngPrice = null,
      robDepDate = null,
      robDepDateIssue = null,
      robDepDatePaid = null,
      robDepBankSlip = [],
      robDepOtherFee = null,
      robDepInvoice = [],
      suppliedVlsfo = null,
      suppliedVlsfoPrice = null,
      suppliedLsmgo = null,
      suppliedLsmgoPrice = null,
      suppliedOtherFee = null,
      suppliedLng = null,
      suppliedLngPrice = null,
      suppliedDate = null,
      suppliedDateIssue = null,
      suppliedDatePaid = null,
      suppliedInvoice = [],
      robArrBdn = [],
      robDepBdn = [],
      suppliedBdn = [],
      suppliedBankSlip = [],
      dueDate = null,
    } = result.data.portBunkerData || {}
    const suppliedBdnList=suppliedBdn?.split('&&&').map(item=>{return {url:item,name:getFileName(item)}})
    const suppliedInvoiceList=suppliedInvoice?.split('&&&').map(item=>{return {url:item,name:getFileName(item)}})
    portFormObj.value.id = id
    portFormObj.value.recordData = [
      {
        name: 'ROB ARR(mt)',
        VLSFO: robArrVlsfo || 0, 
        VLSFOPRICE: robArrVlsfoPrice || 0,
        LSMGO: robArrLsmgo || 0,
        LSMGOPRICE: robArrLsmgoPrice || 0,
        LNG: robArrLng || 0,
        LNGPRICE: robArrLngPrice || 0,
        OTHERFEE: robArrOtherFee || 0,
        DATETIME: robArrDate,
        INVOICE: robArrInvoice!=null?[{url:robArrInvoice ,name:getFileName(robArrInvoice)}]:[],
        BDN: robArrBdn!=null?[{url:robArrBdn,name:getFileName(robArrBdn)}]:[],
        DATEISSUE: robArrDateIssue,
        DATEPAID: robArrDatePaid,
        BANKSLIP: robArrBankSlip!=null?[{url:robArrBankSlip,name:getFileName(robArrBankSlip)}]:[],
        DUEDATE: dueDate
      },
      {
        name: 'ROB DEP(mt)',
        VLSFO: robDepVlsfo || 0,
        VLSFOPRICE: robDepVlsfoPrice || 0,
        LSMGO: robDepLsmgo || 0,
        LSMGOPRICE: robDepLsmgoPrice || 0,
        LNG: robDepLng || 0,
        LNGPRICE: robDepLngPrice || 0,
        OTHERFEE: robDepOtherFee || 0,
        BDN: robDepBdn!=null?[{url:robDepBdn,name:getFileName(robDepBdn)}]:[],
        DATETIME: robDepDate,
        INVOICE: robDepInvoice!=null?[{url:robDepInvoice,name:getFileName(robDepInvoice)}]:[],
        DATEISSUE: robDepDateIssue,
        DATEPAID: robDepDatePaid,
        BANKSLIP: robDepBankSlip!=null?[{url:robDepBankSlip,name:getFileName(robDepBankSlip)}]:[],
        DUEDATE: dueDate
      },
      {
        name: "SUPPLIED",
        VLSFO: suppliedVlsfo || 0,
        VLSFOPRICE: suppliedVlsfoPrice || 0,
        LSMGO: suppliedLsmgo || 0,
        LSMGOPRICE: suppliedLsmgoPrice || 0,
        LNG: suppliedLng || 0,
        LNGPRICE: suppliedLngPrice || 0,
        OTHERFEE: suppliedOtherFee || 0,
        BDN: suppliedBdn!=null?suppliedBdnList:[],
        DATETIME: suppliedDate,
        INVOICE: suppliedInvoice!=null?suppliedInvoiceList:[],
        DATEISSUE: suppliedDateIssue,
        DATEPAID: suppliedDatePaid,
        BANKSLIP: suppliedBankSlip!=null?[{url:suppliedBankSlip,name:getFileName(suppliedBankSlip)}]:[],
        DUEDATE: dueDate
      },
      {
        name: '',
        VLSFO: null,
        VLSFOPRICE: null,
        LSMGO: null,
        LSMGOPRICE: null,
        LNG: null,
        LNGPRICE: null,
        OTHERFEE: null,
        DATETIME: null,
        BDN: null,
        INVOICE: null,
        DATEISSUE: null,
        DATEPAID: null,
        BANKSLIP: null,
        DUEDATE: null
      },
      {
        name: '',
        VLSFO: null,
        VLSFOPRICE: null,
        LSMGO: null,
        LSMGOPRICE: null,
        LNG: null,
        LNGPRICE: null,
        OTHERFEE: null,
        DATETIME: null,
        BDN: null,
        INVOICE: null,
        DATEISSUE: null,
        DATEPAID: null,
        BANKSLIP: null,
        DUEDATE: null
      }
    ]
  }
  const activeTab=ref(0)
  const tabChange = (value) => { 
    activeTab.value = value
    updateDialogWidth()
  }
  const inForMationModal = ref()
  const operationRecordModal = ref()
  const epdafdaInforef = ref()
  const bunkerInforef = ref()
  const saveOk = () => {
    dialogPort.value = false;
    activeTab.value = 0
    refreshTable()
  }

  const exportClickEvent = (type)=>{
    queryParams.type = type
    downloadFile("/shipping/schedule/export",queryParams,"schedule.xlsx")
  }

    const exportEpdafda = ( )=>{ 
    let file = queryParams.vesselName 
    if(queryParams.voyageNo != null){
       file += " " + queryParams.voyageNo
    }
    file += " EPDA+FDA支付表.xlsx"
    downloadFile("/shipping/schedule/exportEpdaFda",queryParams,file)
  }

/**
 * 总计计算
 * VLSFO*PRICE+LSMGO*PRICE+LNG*PRICE+OTHERFEE=AMOUNT

**/ 
  const robArrAmount=computed(()=>{
    let total = 0;
    
    const { LNGPRICE,LSMGOPRICE,VLSFOPRICE, VLSFO, LSMGO, LNG,OTHERFEE } =  portFormObj.value.recordData[0] || {};
    total= (VLSFO || 0) * (VLSFOPRICE || 0) + (LSMGO || 0) * (LSMGOPRICE || 0) + (LNG || 0) * (LNGPRICE || 0)+ (OTHERFEE || 0) ;
    return total.toFixed(3);;
  })
  const suppliedAmount=computed(()=>{
    let total = 0;
    const { LNGPRICE,LSMGOPRICE,VLSFOPRICE, VLSFO, LSMGO, LNG,OTHERFEE } =  portFormObj.value.recordData[2] || {};
    total= (VLSFO || 0) * (VLSFOPRICE || 0) + (LSMGO || 0) * (LSMGOPRICE || 0) + (LNG || 0) * (LNGPRICE || 0)+ (OTHERFEE || 0) ;
    return total.toFixed(2);
  })
  const  robDepAmount=computed(()=>{
    let total = 0;
    const { LNGPRICE,LSMGOPRICE,VLSFOPRICE, VLSFO, LSMGO, LNG,OTHERFEE } =  portFormObj.value.recordData[1] || {};
    total= (VLSFO || 0) * (VLSFOPRICE || 0) + (LSMGO || 0) * (LSMGOPRICE || 0) + (LNG || 0) * (LNGPRICE || 0)+ (OTHERFEE || 0) ;
    return total.toFixed(3);
  })

// 获取文件名称
function getFileName(name) {
  if (name == null) {
    return name;
  }
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}



</script>

<style scoped lang="scss">
  .el-table .cell {
    text-align: center !important;
    color: #888 !important;
    white-space: nowrap!important;
  }
  .el-table__expand-column .cell {
    display: none;
  }
.detail-table-add{
  ::v-deep.el-table td.el-table__cell div {
    overflow: visible !important;
  }
  ::v-deep .el-form-item__error{
    line-height:0.5 !important;
  }
  ::v-deep .el-input__inner {
    height: 28px !important;
  }
  ::v-deep .el-form-item__content{
    height: 28px !important;
    .el-input__wrapper{
      height: 28px!important;
    }
  }
}
  .c-expand {
    color: #888;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    cursor: pointer;
    width: 100%;
    height: 100%;
  }

  .c-expand i {
    font-size: 16px;
  }

  .c-expand i.expand {
    font-size: 16px;
    transform: rotate(90deg);
    transition: all 0.25s;
  } 
  .header-wrapper {
    border: 1px solid #ebeef5;
    border-bottom: none;
    padding: 10px;
  }

  .daf-table {
    margin: 0;
    padding: 0;
  }

  .tips {
    text-align: right;
    margin: 6px 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .el-button {
      margin-right: 14px;
      // width: 6px !important;
      // height: 6px;
    }
  }

  .el-icon-arrow-right {
    margin-right: 10px;
    margin-left: 10px;
    cursor: pointer;
  }

  .pane-footer {
    margin-top: 20px;
    text-align: right;
  } 
 
  .schedule .el-form-item {
    margin-bottom: 3px !important;
  }
 
  ::v-deep .el-form-item{
    margin-bottom: 3px !important;
  }

  .schedule{
    position: relative;
     
  }
  .el-table .cell{
     padding: 0 12px !important;
  }
  ::v-deep .bunker-content .el-input__prefix{
    display: none!important;
  }
  ::v-deep .bunker-content .el-input-number.is-without-controls .el-input__wrapper{
    padding: 0 12px !important;
  }

  ::v-deep .bunker-content .el-table .cell{
     padding: 0 12px !important;
  }
  .header_title{
    font-size: 12px;
    font-weight: 600; 
    position: absolute;
    top: 32px;
    right: 20px;
  }
  my-custom-dropdown .el-select-dropdown__item {
  display: inline-block; /* 或者其他布局方式 */
  margin-right: 10px; /* 根据需要调整间距 */
}
.brunk-upload{
  display: flex;
  align-items: center;
  >span{
    display: inline-block;
    text-align: left;
    width: 71px;
  }
}
</style>